import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { http, API_PATH } from '../utils/http';
import { message, Spin, Image, Typography, Button, Card, Empty, Modal, Input, Tag, Row, Col, Descriptions, Space } from 'antd';
import { ArrowLeftOutlined, EditOutlined, RedoOutlined, DownloadOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';

const { Title, Text } = Typography;

// Interfaces (redefined here, consider moving to a shared types file)
interface TaskResultItem {
    type: string;
    index: number;
    url: string;
}

interface ImageTaskItem {
    id: string;
    article_id: string | null;
    article_text: string | null;
    article_type: string;
    status: string; // General status from the task entry itself
    created_at: number;
    updated_at: number;
    img_desc: string | null;
    img_url: string | null;
    img_index: number | null;
    task_id: string | null; // This is the AI service specific task_id
    task_status: string | null; // Status from the AI generation service
    task_status_msg: string | null;
    task_result: TaskResultItem[] | null;
    error: string | null;
}

// For update responses (similar to IllustrationPage)
interface UpdateResponse {
    task_id: string; // This is likely the ImageTaskItem.id
    updated_at: number;
}

// Interface for regenerate image response (from IllustrationPage)
interface RegenerateImageData {
    task_id: string; // This is likely the AI service's task_id
    message_id: string;
    success: boolean;
    submitted_at: number;
}

const placeholderWrapperStyle: React.CSSProperties = {
    padding: '20px',
    border: '1px dashed #d9d9d9',
    borderRadius: '8px',
    background: '#fafafa',
    minHeight: '200px',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    textAlign: 'center',
};

const IllustrationTaskDetail: React.FC = () => {
    const navigate = useNavigate();
    const { taskId } = useParams<{ taskId: string }>(); // This will be ImageTaskItem.id
    const [loading, setLoading] = useState(true);
    const [isRegenerating, setIsRegenerating] = useState(false); // Specific loading state for regeneration
    const [taskDetail, setTaskDetail] = useState<ImageTaskItem | null>(null);
    const [isEditingContent, setIsEditingContent] = useState(false);
    const [editingContentText, setEditingContentText] = useState('');
    const [isEditingDescription, setIsEditingDescription] = useState(false);
    const [editingDescriptionText, setEditingDescriptionText] = useState('');

    const fetchTaskDetail = useCallback(async () => {
        if (!taskId) return;
        setLoading(true);
        try {
            // The API is GET_IMAGE_TASK_BY_ID, which implies it returns a single item, not an array.
            // The response type for http.get should be ImageTaskItem, not ImageTaskItem[]
            const response = await http.get<ImageTaskItem>(
                API_PATH.ILLUSTRATION.GET_IMAGE_TASK_BY_ID,
                { task_id: taskId } // Parameter name as per your API spec
            );
            response.onSuccess(() => {
                // Assuming response.data contains the single ImageTaskItem object
                if (response.data && !Array.isArray(response.data)) {
                    setTaskDetail(response.data);
                } else {
                    message.error('获取任务详情失败：无效的数据格式');
                    setTaskDetail(null); // Clear out any old data
                }
            }).onError((_code, msg) => {
                message.error(`获取任务详情失败: ${msg}`);
                setTaskDetail(null);
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            message.error('网络请求异常');
            setTaskDetail(null);
        } finally {
            setLoading(false);
        }
    }, [taskId]);

    useEffect(() => {
        fetchTaskDetail();
    }, [fetchTaskDetail]);

    const handleBack = () => {
        navigate('/illustration-center'); // Navigate back to the list view
    };

    const openEditContentModal = () => {
        setEditingContentText(taskDetail?.article_text || '');
        setIsEditingContent(true);
    };

    const saveArticleContent = async () => {
        if (!taskDetail) return;
        setLoading(true);
        try {
            const response = await http.post<UpdateResponse>(
                API_PATH.ARTICLE_CENTER.UPDATE_CONTENT, // Reusing from IllustrationPage logic
                { task_id: taskDetail.id, article_text: editingContentText }
            );
            response.onSuccess(() => {
                message.success('文章内容已更新');
                setIsEditingContent(false);
                fetchTaskDetail(); // Refresh data
            }).onError((_code, msg) => {
                message.error(`更新文章内容失败: ${msg}`);
            });
        } catch (error) {
            console.error('保存文章内容失败:', error);
            message.error('保存文章内容失败');
        } finally {
            setLoading(false);
        }
    };

    const openEditDescriptionModal = () => {
        setEditingDescriptionText(taskDetail?.img_desc || '');
        setIsEditingDescription(true);
    };

    const saveImageDescription = async () => {
        if (!taskDetail) return;
        setLoading(true);
        try {
            const response = await http.post<UpdateResponse>(
                API_PATH.ARTICLE_CENTER.UPDATE_DESCRIPTION, // Reusing from IllustrationPage logic
                { task_id: taskDetail.id, img_desc: editingDescriptionText }
            );
            response.onSuccess(() => {
                message.success('图片描述已更新');
                setIsEditingDescription(false);
                fetchTaskDetail(); // Refresh data
            }).onError((_code, msg) => {
                message.error(`更新图片描述失败: ${msg}`);
            });
        } catch (error) {
            console.error('保存图片描述失败:', error);
            message.error('保存图片描述失败');
        } finally {
            setLoading(false);
        }
    };

    const _handleRegenerateImageCore = async () => {
        if (!taskDetail) return;
        setIsRegenerating(true);
        try {
            const response = await http.post<RegenerateImageData>(
                API_PATH.ARTICLE_CENTER.REGENERATE_IMAGE,
                { task_id: taskDetail.id, priority: 5 }
            );
            response.onSuccess(() => {
                message.success('图片重新生成任务已提交，请稍后刷新查看状态。');
                fetchTaskDetail();
            }).onError((_code, msg) => {
                message.error(`重新生成图片失败: ${msg}`);
            });
        } catch (error) {
            console.error('重新生成图片请求异常:', error);
            message.error('重新生成图片请求异常');
        } finally {
            setIsRegenerating(false);
        }
    };

    const confirmAndRegenerateImage = () => {
        if (!taskDetail) return;
        Modal.confirm({
            title: '确认重新生成',
            content: '您确定要重新生成这张图片吗？此操作可能会影响现有结果。',
            okText: '确定重新生成',
            cancelText: '取消',
            onOk: () => {
                _handleRegenerateImageCore();
            },
        });
    };

    const handleDownloadImage = async (imageUrl: string, filenameBase?: string) => {
        try {
            const response = await fetch(imageUrl);
            const blob = await response.blob();
            const base = filenameBase || taskDetail?.id || 'image';
            const finalFilename = `${base}.png`;

            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = finalFilename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(link.href);
            message.success('图片已开始下载');
        } catch (error) {
            console.error('下载图片失败:', error);
            message.error('下载图片失败，请检查链接或网络。');
        }
    };

    const renderStatusTag = (taskStatus: string | null, generalStatus: string) => {
        const currentStatus = taskStatus || generalStatus;
        let color = 'default';
        let displayText = currentStatus || '未知';
        switch (currentStatus?.toLowerCase()) {
            case 'succeed': color = 'green'; displayText = '成功'; break;
            case 'failed': color = 'red'; displayText = '失败'; break;
            case 'processing': color = 'blue'; displayText = '处理中'; break;
            case 'pending': color = 'gold'; displayText = '待执行'; break;
            case 'submitted': color = 'cyan'; displayText = '已提交'; break;
            default: if (!currentStatus) displayText = '未知'; break;
        }
        return <Tag color={color}>{displayText}</Tag>;
    };

    // Helper function for rendering placeholders when no image is available
    const renderImagePlaceholder = (status: string | null, errorMsg?: string | null, detailError?: string | null) => {
        let placeholderContent;
        switch (status?.toLowerCase()) {
            case 'processing':
            case 'pending':
            case 'submitted':
                placeholderContent = <div style={placeholderWrapperStyle}><Spin size="large" tip="图片生成中，请稍候..." /></div>;
                break;
            case 'failed':
                placeholderContent = (
                    <div style={placeholderWrapperStyle}>
                        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={<Text type="danger" strong>图片生成失败</Text>} />
                        {errorMsg && <Text type="secondary" style={{ marginTop: 8 }}>原因: {errorMsg}</Text>}
                        {detailError && !errorMsg && <Text type="secondary" style={{ marginTop: 8 }}>错误详情: {detailError}</Text>}
                        <Button
                            type="primary"
                            icon={<RedoOutlined />}
                            onClick={confirmAndRegenerateImage}
                            loading={isRegenerating}
                            style={{ marginTop: 16 }}
                        >
                            重新生成
                        </Button>
                    </div>
                );
                break;
            case 'succeed': // Succeeded but no image URL
                placeholderContent = <div style={placeholderWrapperStyle}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="图片处理成功，但未能获取有效图片链接。" /></div>;
                break;
            default:
                placeholderContent = <div style={placeholderWrapperStyle}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无图片或图片尚未生成。" /></div>;
                break;
        }
        return placeholderContent;
    };

    if (loading && !isRegenerating) {
        return <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}><Spin size="large" tip="加载任务详情中..." /></div>;
    }

    if (!taskDetail) {
        return (
            <div style={{ textAlign: 'center', marginTop: '50px' }}>
                <Empty description="未能加载任务详情或任务不存在。" />
                <Button type="primary" onClick={handleBack} style={{ marginTop: 20 }}>返回列表</Button>
            </div>
        );
    }

    const mainImageUrl = taskDetail.task_result?.[0]?.url || taskDetail.img_url;
    const currentActualStatus = taskDetail.task_status || taskDetail.status;

    return (
        <div className="min-h-screen bg-gray-50 p-4 md:p-8">
            <Card className="max-w-4xl mx-auto shadow-lg">
                <Row gutter={[16, 16]} align="middle" className="mb-6 pb-4 border-b">
                    <Col>
                        <Button onClick={handleBack} icon={<ArrowLeftOutlined />}>返回列表</Button>
                    </Col>
                    <Col flex="auto">
                        <Title level={3} style={{ margin: 0 }}>任务详情: {taskDetail.id}</Title>
                    </Col>
                </Row>

                <Descriptions bordered column={{ xxl: 2, xl: 1, lg: 1, md: 1, sm: 1, xs: 1 }}>
                    <Descriptions.Item label="任务ID (AI)">{taskDetail.task_id}</Descriptions.Item>
                    <Descriptions.Item label="状态">{renderStatusTag(taskDetail.task_status, taskDetail.status)}</Descriptions.Item>
                    <Descriptions.Item label="创建时间">{new Date(taskDetail.created_at).toLocaleString()}</Descriptions.Item>
                    <Descriptions.Item label="最后更新时间">{new Date(taskDetail.updated_at).toLocaleString()}</Descriptions.Item>
                    {taskDetail.error && (
                        <Descriptions.Item label="错误信息" span={2}>
                            <Text type="danger">{taskDetail.error}</Text>
                        </Descriptions.Item>
                    )}
                </Descriptions>

                <div className="my-8 text-center">
                    <Title level={4} className="mb-4">生成图片</Title>
                    {mainImageUrl ? (
                        <>
                            <div style={{ marginBottom: '16px' }}>
                                <Image
                                    src={mainImageUrl}
                                    alt={taskDetail.img_desc || '生成图片'}
                                    style={{
                                        display: 'block',
                                        margin: '0 auto',
                                        maxHeight: 400,
                                        maxWidth: '100%',
                                        border: '1px solid #f0f0f0',
                                        borderRadius: '8px'
                                    }}
                                />
                            </div>
                            {currentActualStatus?.toLowerCase() === 'succeed' && (
                                <div style={{ textAlign: 'center' }}>
                                    <Space direction="horizontal" size="middle">
                                        <Button
                                            icon={<RedoOutlined />}
                                            onClick={confirmAndRegenerateImage}
                                            loading={isRegenerating}
                                        >
                                            重新生成
                                        </Button>
                                        <Button
                                            type="primary"
                                            icon={<DownloadOutlined />}
                                            onClick={() => handleDownloadImage(mainImageUrl, taskDetail.id)}
                                        >
                                            下载图片
                                        </Button>
                                    </Space>
                                </div>
                            )}
                        </>
                    ) : (
                        renderImagePlaceholder(currentActualStatus, taskDetail.task_status_msg, taskDetail.error)
                    )}
                </div>

                <Row gutter={[32, 32]} className="mt-8">
                    <Col xs={24} md={12}>
                        <Card type="inner" title={<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><span>图片描述</span> <Button icon={<EditOutlined />} size="small" onClick={openEditDescriptionModal} loading={loading && !isRegenerating}>编辑</Button></div>}>
                            {taskDetail.img_desc ? (
                                <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeRaw]}>{taskDetail.img_desc}</ReactMarkdown>
                            ) : (
                                <Text type="secondary">暂无图片描述。</Text>
                            )}
                        </Card>
                    </Col>
                    <Col xs={24} md={12}>
                        <Card type="inner" title={<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><span>文章内容</span> <Button icon={<EditOutlined />} size="small" onClick={openEditContentModal} loading={loading && !isRegenerating}>编辑</Button></div>}>
                            {taskDetail.article_text ? (
                                <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeRaw]}>{taskDetail.article_text}</ReactMarkdown>
                            ) : (
                                <Text type="secondary">暂无关联文章内容。</Text>
                            )}
                        </Card>
                    </Col>
                </Row>
            </Card>

            <Modal
                title="编辑文章内容"
                open={isEditingContent}
                onOk={saveArticleContent}
                onCancel={() => setIsEditingContent(false)}
                confirmLoading={loading && !isRegenerating}
                width={'80vw'}
                okText="保存"
                cancelText="取消"
            >
                <Input.TextArea
                    value={editingContentText}
                    onChange={(e) => setEditingContentText(e.target.value)}
                    rows={15}
                    placeholder="请输入文章内容 (支持Markdown)"
                />
            </Modal>

            <Modal
                title="编辑图片描述"
                open={isEditingDescription}
                onOk={saveImageDescription}
                onCancel={() => setIsEditingDescription(false)}
                confirmLoading={loading && !isRegenerating}
                width={'80vw'}
                okText="保存"
                cancelText="取消"
            >
                <Input.TextArea
                    value={editingDescriptionText}
                    onChange={(e) => setEditingDescriptionText(e.target.value)}
                    rows={10}
                    placeholder="请输入图片描述 (支持Markdown)"
                />
            </Modal>
        </div>
    );
};

export default IllustrationTaskDetail; 